package com.example.demo.bean.queue.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class DisruptorUtil {
    static Disruptor<OutputEvent> disruptor = null;

    static{
        OutputEventFactory factory = new OutputEventFactory();
        // 负责对通过 Disruptor 进行交换的数据（事件）进行存储和更新
        int ringBufferSize = 1024;
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable runnable) {
                return new Thread(runnable);
            }
        };
        disruptor =
                new Disruptor<OutputEvent>(factory, ringBufferSize, (Executor) Executors.defaultThreadFactory());
        //设置一个消费者
        disruptor.handleEventsWith(new OutputConsumer("1"));
        disruptor.start();
    }

    /**
     * 生产数据
     * @param output
     */
    public static void producer(OutputEvent output){
        RingBuffer<OutputEvent> ringBuffer = disruptor.getRingBuffer();
        OutputEventProducer producer = new OutputEventProducer(ringBuffer);
        producer.onData(output.getId());
    }
}
